﻿using myBackupService.Backup;
using myBackupService.Model;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using TouchSocket.Core;
using TouchSocket.Http;
using TouchSocket.Sockets;
namespace myBackupService
{
    public partial class frmMain : Form
    {
        HttpService service = new HttpService();
        public frmMain()
        {
            InitializeComponent();
        }

        private async void frmMain_Load(object sender, EventArgs e)
        {
            try
            {
                await Intialize();
                toolStripStatusLabel_status.Text = "服务已启动，端口：" + BackupConfig.Instance.Port;
            }
            catch (Exception)
            {
                MessageBox.Show("初始化失败，请检查端口是否被占用或其他错误。","错误");
                toolStripStatusLabel_status.Text = "服务启动失败，请检查端口["+ BackupConfig.Instance.Port + "]是否被占用。" ;
            }
       
        }
        private async Task Intialize()
        {
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
            await service.SetupAsync(new TouchSocketConfig().SetListenIPHosts(BackupConfig.Instance.Port)
             .ConfigureContainer(a =>
             {
                 a.AddConsoleLogger();
                 a.AddEasyLogger((level, message, tag, exception) =>
                 {
                     this.Invoke(new Action(() =>
                     {
                         richTextBox1.AppendText( message.ToString());
                     }));
                 }, LogLevel.Debug);    
             })
             .ConfigurePlugins(a =>
             {
                 a.Add<GetCatalogHttpPlug>();
                 a.Add<DownloadHttpPlug>();
                 a.UseHttpStaticPage()
                 .SetNavigateAction(request =>
                 {
                     //此处可以设置重定向
                     return request.RelativeURL;
                 })
                 .SetResponseAction(response =>
                 {
                     //可以设置响应头
                 });
                 //.AddFolder("html/");//添加静态页面文件夹
                 //default插件应该最后添加，其作用是
                 //1、为找不到的路由返回404
                 //2、处理 header 为Option的探视跨域请求。
                 a.UseDefaultHttpServicePlugin();
             }));
            await service.StartAsync();
        }

        private void btn_setting_Click(object sender, EventArgs e)
        {
            frmSetting frmSetting = new frmSetting();
            frmSetting.ShowDialog();
        }
    }
}
